const path = require('path');
const baseConfig = require('./webpack.base.js');
const merge = require('webpack-merge');
const Happypack = require('happypack');
const os = require('os');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const HtmlWebpackInjectAttributesPlugin = require('html-webpack-inject-attributes-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const {PurgeCSSPlugin} = require('purgecss-webpack-plugin');
const glob = require('glob');

// 多线程设置
const happypackCommonConfig = {
  debug: false,
  threadPool: Happypack.ThreadPool({ size: os.cpus().length })
};

const webpackConfig = merge.smart(baseConfig, {
  // 生产环境
  mode: 'production',
  // 生产环境output配置
  output: {
    filename: 'js/[name]_[chunkhash:8].bundle.js',
    path: path.join(process.cwd(), './app/public/dist/prod'),
    publicPath: '/dist/prod',
    crossOriginLoading: 'anonymous'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          'happypack/loader?id=css'
        ]
      },
      {
        test: /\.js$/,
        include: [path.resolve(process.cwd(), './app/pages')],
        use: [
          'happypack/loader?id=js'
        ]
      }
    ]
  },
  // webpack不会产生大量hints信息 默认warning
  performance: {
    hints: false
  },
  plugins: [
    // 每次build前，清空public/dist
    new CleanWebpackPlugin(['public/dist'], {
      root: path.resolve(process.cwd(), './app/'),
      exclude: [],
      verbose: true,
      dry: false
    }),
    // 提取css的公共部分，有效利用缓存
    new MiniCssExtractPlugin({
      chunkFilename: 'css/[name].[contenthash:8].bundle.css'
    }),
    // 优化并压缩css资源
    new CssMinimizerPlugin(),
    // 多线程打包js加快打包速度
    new Happypack(Object.assign({
      id: 'js',
      loaders: [`babel-loader?${JSON.stringify({
        presets: ['@babel/preset-env'],
        plugins: ['@babel/plugin-transform-runtime'],
        cacheDirectory: true
      })}`]
    }, happypackCommonConfig)),
    // 多线程打包css加快打包速度
    new Happypack(Object.assign({
      id: 'css',
      loaders: [{
        path: 'css-loader',
        options: {
          importLoaders: 1,
        }
      }]
    }, happypackCommonConfig)),
    // 浏览器在请求资源时，不发送用户的身份凭证
    new HtmlWebpackInjectAttributesPlugin({
      crossorigin: 'anonymous'
    }),
    // 补充还应该要去掉未使用的css
    new PurgeCSSPlugin({
      paths: glob.sync(path.join(process.cwd(), './app/pages/**/*.vue'), { nodir: true }),
      defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || []
    }),
  ],
  optimization: {
    // 使用terserPlugin的并发与缓存，提升压缩阶段的性能
    // 清除console.log
    minimize: true,
    minimizer: [
      new TerserPlugin({
        parallel: os.cpus().length, // 利用多核cpu的优势来加快压缩速度
        cache: true, // 启动缓存来加快构建过程
        terserOptions: {
          compress: {
            drop_console: true // 去掉console.log()
          }
        }
      })
    ]
  }
});

module.exports = webpackConfig;